import { Chart, registerables } from 'chart.js';
import { TrendCardData } from '../types/trendCard';

// 注册Chart.js组件
Chart.register(...registerables);

// 生成趋势图base64图片
export const generateTrendChartImage = (_trend: TrendCardData): Promise<string> => {
  return new Promise((resolve, reject) => {
    try {
      // 创建临时canvas
      const canvas = document.createElement('canvas');
      canvas.width = 400;
      canvas.height = 200;
      
      const ctx = canvas.getContext('2d');
      if (!ctx) {
        reject(new Error('无法获取canvas上下文'));
        return;
      }

      // // 准备数据
      // const labels = trend.dataLines[0]?.data.map(d => {
      //   const date = new Date(d.date);
      //   return `${date.getMonth() + 1}/${date.getDate()}`;
      // }) || [];

      // const chartConfig: ChartConfiguration = {
      //   type: 'line',
      //   data: {
      //     labels,
      //     datasets: trend.dataLines.map((line, index) => ({
      //       label: line.name,
      //       data: line.data.map(d => d.value),
      //       borderColor: line.color,
      //       backgroundColor: line.color + '20',
      //       borderWidth: 3,
      //       tension: 0.1,
      //       pointRadius: 0,
      //       pointHoverRadius: 4,
      //     }))
      //   },
      //   options: {
      //     responsive: true,
      //     maintainAspectRatio: false,
      //     plugins: {
      //       legend: {
      //         display: true,
      //         position: 'top' as const,
      //       },
      //       tooltip: {
      //         mode: 'index' as const,
      //         intersect: false,
      //       },
      //     },
      //     scales: {
      //       x: {
      //         display: true,
      //         title: {
      //           display: true,
      //           text: '日期'
      //         }
      //       },
      //       y: {
      //         display: true,
      //         title: {
      //           display: true,
      //           text: '收益率 (%)'
      //         }
      //       }
      //     }
      //   }
      // };

      // 这里需要实际的Chart.js实例来渲染
      // 由于在Node.js环境中无法直接使用Chart.js，我们返回一个占位符
      resolve('');
    } catch (error) {
      reject(error);
    }
  });
};

// 生成简化版HTML趋势图（CSS版本）
export const generateSimpleTrendHTML = (trend: TrendCardData): string => {
  // 计算数据范围，包括所有数据线
  const allValues = trend.dataLines.flatMap(line => line.data.map(d => d.value));
  const maxValue = Math.max(...allValues);
  const minValue = Math.min(...allValues);
  const range = maxValue - minValue || 1;

  // 生成所有数据线的点位
  const linePaths = trend.dataLines.map(line => {
    const points = line.data.map((d, i) => {
      const x = (i / (line.data.length - 1)) * 100;
      const y = 100 - ((d.value - minValue) / range) * 100;
      return `${x}%,${y}%`;
    }).join(' ');
    
    return {
      name: line.name,
      color: line.color,
      points
    };
  });

  return `
    <div style="
      width: 100%; 
      height: 160px; 
      position: relative; 
      background: #f9fafb; 
      border-radius: 8px; 
      overflow: hidden;
      border: 1px solid #e5e7eb;
    ">
      <!-- 背景网格 -->
      <div style="
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-image: 
          linear-gradient(to right, #e5e7eb 1px, transparent 1px),
          linear-gradient(to bottom, #e5e7eb 1px, transparent 1px);
        background-size: 20px 20px;
        opacity: 0.5;
      "></div>
      
      <!-- Y轴标签 -->
      <div style="position: absolute; left: 8px; top: 10px; font-size: 10px; color: #9CA3AF;">${maxValue.toFixed(1)}%</div>
      <div style="position: absolute; left: 8px; top: 50%; transform: translateY(-50%); font-size: 10px; color: #9CA3AF;">${((maxValue + minValue) / 2).toFixed(1)}%</div>
      <div style="position: absolute; left: 8px; bottom: 10px; font-size: 10px; color: #9CA3AF;">${minValue.toFixed(1)}%</div>
      
      <!-- 趋势线容器 -->
      <div style="position: absolute; top: 20px; left: 40px; right: 20px; bottom: 30px;">
        <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none" style="overflow: visible;">
          ${linePaths.map(line => `
            <polyline
              fill="none"
              stroke="${line.color}"
              stroke-width="2"
              points="${line.points}"
              vector-effect="non-scaling-stroke"
            />
          `).join('')}
        </svg>
      </div>
      
      <!-- X轴标签 -->
      <div style="position: absolute; bottom: 8px; left: 40px; font-size: 10px; color: #9CA3AF;">
        ${new Date(trend.dateRange.start).toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })}
      </div>
      <div style="position: absolute; bottom: 8px; right: 20px; font-size: 10px; color: #9CA3AF;">
        ${new Date(trend.dateRange.end).toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })}
      </div>
    </div>
  `;
}; 